package com.example.yrdev.ordering_system.homeOptions;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.yrdev.ordering_system.R;
import com.example.yrdev.ordering_system.Utils.GlobalFunction;
import com.example.yrdev.ordering_system.Utils.MIScanner;

import java.util.Locale;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by yrdev on 9/5/16.
 */
public class PaymentDialog extends Dialog {
  private final   String USER_PURCHASE_key="USER_PURCHASE_KEY";
    private Context context;
    private String tit;
    private Activity activity;
    private Integer paymentType;
    private final String fixPurchasePrice="5.5";

    MIScanner reader;
    private callBack callBack;

    public interface callBack{
        void getCurAmount(Integer amount);
        void done();
        void standbyMode();


    }

    public void setCallBack(PaymentDialog.callBack callBack) {
        this.callBack = callBack;
    }

    public PaymentDialog(Context context){
        super(context);
        this.context=context;
        requestWindowFeature(Window.FEATURE_NO_TITLE);

    }

    public void setPaymentType(Integer paymentType) {
        this.paymentType = paymentType;

        
    }

    public void hideEditPriceBut(){

        try {
            if (paymentType==0){
                edit_price_but.setVisibility(View.INVISIBLE);

            }else {
                edit_price_but.setVisibility(View.VISIBLE);
            }


        }catch (Exception e){

        }

    }


    public String getTit() {
        return tit;
    }

    public PaymentDialog(Context context,Integer paymentType,Activity activity){
        super(context);
        String [] titles={"定额消费","随机消费","您的消费"};

        this.context=context;
        this.paymentType=paymentType;

        this.tit=titles[paymentType];
        this.activity=activity;
        requestWindowFeature(Window.FEATURE_NO_TITLE);


    }
    public void setPaymentValue(Double cost){


        price.setText(GlobalFunction.checkedPriceText(cost));

    }



   public int getPurchasePrice(){
       SharedPreferences preferences= activity.getPreferences(Context.MODE_PRIVATE);
       int purchase_price=preferences.getInt(USER_PURCHASE_key, 0);
       return purchase_price;

   }
    public void savePurchasePrice(Integer newAmount){
        SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(USER_PURCHASE_key, newAmount).apply();


        //editor.putFloat(USER_PURCHASE_key,(float)newAmount);


    }



    @InjectView(R.id.dialog_title)TextView dial_tit;
    @InjectView(R.id.price)EditText price;
    @InjectView(R.id.swipe_stat)TextView swipe_stat;
    @InjectView(R.id.edit_price_but)Button  edit_price_but;
    @InjectView(R.id.purchaseBalance)TextView purchaseBalance;

   @InjectView(R.id.user_other_nominal)LinearLayout user_other_nominal;
    @InjectView(R.id.prev_balance)TextView prev_balance;
    @InjectView(R.id.cur_balance)TextView current_balance;
//    @InjectView(R.id.amountTag)TextView amountTag;
   @InjectView(R.id.purchaseMode)LinearLayout purchaseMode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.payment_layot);
        initView();

    }


    public void changeTitle(String tit){

        dial_tit.setText(tit);

     }

    public  void changePrice(String amount){
        price.setText(amount);
    }

  public Integer getCurrentPrice(){
       Double temp=0.;
        if (price.getText().length()>0){
            temp=Double.valueOf(price.getText().toString());

        }
        temp=temp*100;

        return temp.intValue();


    }




    public  void initView(){
        ButterKnife.inject(this);
        getWindow().setBackgroundDrawableResource(R.drawable.dialog_background);
      dial_tit.setText(tit);

//        if (tit.equals("退款"))
//        amountTag.setText("退款余额 : ");

    price.setOnEditorActionListener(keyboardEditor());

    switch (paymentType){
        case 0://定额消费
        {
            price.setText(fixPurchasePrice);
            if (getCurrentPrice()>0){
                editMode(false);
            }else {
                editMode(true);
                activateEditText();
            }


            //hideEditPriceBut();
        }
            break;

       case 1:{//随机消费

          //   price.setText("");
          activateEditText();

            price.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    price.setCursorVisible(true);
                    price.getText().clear();
                    returnStandbyMode();

                }
            });

        }
            break;

        case 2:{//其他

            edit_price_but.setVisibility(View.GONE);
            swipe_stat.setVisibility(View.VISIBLE);
           editMode(false);

        }
        break;
    }




    user_other_nominal.setVisibility(View.GONE);




}

  private   boolean hideField=false;


    void  hidePriceField(){

        price.setVisibility(View.GONE);
        hideField=true;


    }

    void showFixPricePurchaseCost(Double cost){//显示定额金额

        price.setVisibility(View.VISIBLE);
        price.setText(String.format(Locale.getDefault(),"%.2f",cost));
    }


private void activateEditText(){
    price.getText().clear();
    price.requestFocus();
//    price.setCursorVisible(true);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);//直接弹出输入框\

}
    private  void standbyPurchase(Boolean stat){
        if (stat){
            swipe_stat.setText("请刷卡。。。");
        }else {
            swipe_stat.setText("请输入消费余额。。。");
        }
    }

    public void showUserOtherNominal(Double prevBalance,Double currentBalance){

        prev_balance.setText(String.valueOf(prevBalance)+"元");
        current_balance.setText(String.valueOf(currentBalance)+"元");
        user_other_nominal.setVisibility(View.VISIBLE);
        swipe_stat.setVisibility(View.GONE);
        hideUserOtherNominal();

        if (callBack!=null)
            callBack.done();

    }

   public void showOtherNominal(Double reduceAmount,Double prevBalance,Double currentBalance){

        String reduceVal=String.format(Locale.getDefault(),"%.2f",reduceAmount);//消费余额
        reduceVal=reduceVal+"元";
        purchaseMode.setVisibility(View.GONE);
        purchaseBalance.setText(reduceVal);



        prev_balance.setText(String.valueOf(prevBalance)+"元");
        current_balance.setText(String.valueOf(currentBalance)+"元");
        user_other_nominal.setVisibility(View.VISIBLE);
        swipe_stat.setVisibility(View.GONE);
        hideUserOtherNominal();

        if (callBack!=null)
            callBack.done();

    }

    private void hideUserOtherNominal(){

        new java.util.Timer().schedule(new TimerTask() {
            @Override
            public void run() {






                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {



                        user_other_nominal.setVisibility(View.GONE);

                        if (paymentType!=0)
                         returnStandbyMode();
                    else
                        startPurchaseMode();

                        if (paymentType==1)//随机消费模式
                        {
                            standbyPurchase(false);
                            price.getText().clear();
                            InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.showSoftInput(price, InputMethodManager.SHOW_IMPLICIT);
                        price.setCursorVisible(true);
                        }


                    }
                });
               // GlobalFunction.ToastAlert(context,"ccasd");

            }

        },1500);


    }

    public boolean checkPrice(){
    boolean stat=false;

      Integer price_val=getCurrentPrice();

        if (price_val<=0){

            editMode(true);
            GlobalFunction.ToastAlert(context, "请确认此消费余额");

        }else {
            standbyPurchase(true);
            savePurchasePrice(price_val/100);
            editMode(false);
            stat=true;

        }
        return stat;

    }

    @OnClick(R.id.edit_price_but)
    void editPrice(){



        if (checkPrice()){//检查
          startPurchaseMode();


        }




    }
    @OnClick(R.id.close)
    void closeDialog(){
        dismiss();

    }

  public void  startPurchaseMode(){
        swipe_stat.setVisibility(View.VISIBLE);
        edit_price_but.setVisibility(View.GONE);

      purchaseMode.setVisibility(View.VISIBLE);
      if (hideField)
          price.setVisibility(View.GONE);
    }

    private  void returnStandbyMode(){
        purchaseMode.setVisibility(View.VISIBLE);
        swipe_stat.setVisibility(View.GONE);
        edit_price_but.setVisibility(View.VISIBLE);
        if (callBack!=null){
            callBack.standbyMode();

        }
    }

private void editMode(Boolean stat){
    if (stat){

        price.setEnabled(true);
        price.requestFocus();
        GlobalFunction.ToastAlert(context, "请确认此消费余额");
        GlobalFunction.showKeyboardForEditText(context,price);
        swipe_stat.setText("请输入消费余额");
    }else {

        if (paymentType==0||paymentType==2)//定额消费
          price.setEnabled(false);
        else
        {
            View view = this.getCurrentFocus();
            if (view != null) {

                InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
           price.setCursorVisible(false);
        }

        if (callBack!=null)
        {
            Double temp=100*Double.valueOf(price.getText().toString());
             callBack.getCurAmount(temp.intValue());

        }

            swipe_stat.setText("请刷卡。。。");
    }
}

    private TextView.OnEditorActionListener keyboardEditor(){

        TextView.OnEditorActionListener editorActionListener=new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
               if (actionId== EditorInfo.IME_ACTION_DONE)
               {

                   try {
                   if (checkPrice()){

                       startPurchaseMode();

                   }


                   }catch (Exception e){
                       GlobalFunction.ToastAlert(context,"请确认此消费余额");
                       GlobalFunction.showKeyboardForEditText(context,price);
                   }

               }

                return true;
            }
        };
                return editorActionListener;
    }

}

